package com.linjiahao.nettyBus.handler;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.linjiahao.commonUtil.base.SpringContextUtil;
import com.linjiahao.nettyBus.channel.GlobalChannel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName NettyWebSocketHandler
 * @Description: TODO
 * @Author linjiahao
 * @Date 2022/3/22
 **/
@Slf4j
@Component
public class NettyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {



    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            log.info("websocket协议握手成功");
            GlobalChannel globalChannel = SpringContextUtil.getBeanByClass(GlobalChannel.class);
            AttributeKey<String> tokenKey = globalChannel.getTokenKey();
            String userId = ctx.channel().attr(tokenKey).get();
            if(StringUtils.isBlank(userId)){
                log.info(NettyWebSocketHandler.class+"非法连接");
                ctx.writeAndFlush(new TextWebSocketFrame("非法连接")).addListener(ChannelFutureListener.CLOSE);
            }else {
                globalChannel.bindChannel(userId,ctx.channel());
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("webSocket连接，通道开启,id:{}", ctx.channel().id());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("webSocket断开连接，通道关闭,id:{}", ctx.channel().id());
        GlobalChannel globalChannel = SpringContextUtil.getBeanByClass(GlobalChannel.class);
        Attribute<String> attr = ctx.channel().attr(globalChannel.getTokenKey());
        if (null != attr && null != attr.get()){
            String userId = attr.get();
            globalChannel.removeChannel(userId);
            attr.remove();
            log.info("{}用户连接通道移除",userId);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame webSocketFrame) throws Exception {
        log.info(((TextWebSocketFrame) webSocketFrame).text());
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("dfsffsf"));
    }
}
